package org.genuflex.components
{
	import mx.containers.Panel;
	import org.genuflex.utils.GenuflexDataFunctions;
	import mx.collections.ArrayCollection;
	import flash.ui.Keyboard;
	import flash.events.KeyboardEvent;
	import mx.controls.TextInput;
	import mx.events.CollectionEvent;
	import flash.events.Event;
	
	public class GenuflexListing extends Panel
	{
		public var txtSearch : TextInput;
		
		[Bindable]
		public var searchString : String;			
		
		[Bindable]
		protected var searchFieldArray : Array = ['toSearchableString'];
		
		[Bindable]
		private var _originalDataProvider : ArrayCollection;
		
		[Bindable]
		protected var _dataProvider : ArrayCollection;
		public function set dataProvider(values : ArrayCollection) : void {
			_originalDataProvider = values;

			if (values != null) {
				//Watch for any changes on the orignal data provider
				_originalDataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, resetDataProvider);
				
				//Configure the local data provider
				resetDataProvider();
			}
			else {
				_dataProvider = null;
			}					
		}
		private function resetDataProvider(event : Event = null) : void {
			if (_originalDataProvider != null) {
				_dataProvider = new ArrayCollection(_originalDataProvider.toArray());
				_dataProvider.filterFunction = filterForSearchString;
				_dataProvider.refresh();
			}
			else {
				_dataProvider = null;
			}			
		}								
		protected function filterForSearchString(item : Object) : Boolean {
			var isMatch : Boolean = false;
			
			if (item != null) {
				//Filter by the search string if populated
				if(GenuflexDataFunctions.isNotEmpty(searchString)) {
					isMatch = GenuflexDataFunctions.isSearchMatch(item, searchFieldArray, searchString);
				}
				else {
					isMatch = true;
				}
			}

			return isMatch;
		}
		
		public function handleSearch(searchString : String) : void {
			this.searchString = searchString;
			if (_dataProvider != null) {
				_dataProvider.refresh();
			}
		}
		public function handleShowAll() : void {
			searchString = null;

			if (_dataProvider != null) {			
				_dataProvider.refresh();
			}
		}
	}
}